// 新增机构、编辑机构
import React from 'react';
import { useLocation, useHistory } from 'react-router';
import { observer, useLocalStore } from 'mobx-react-lite';
import { parse } from 'qs';
import { Card, Form, Row, Col, Input, Button, message } from 'antd';
import * as addApi from '~/apis/institution/addApi';
import AjaxSelect from '~/components/AjaxSelect';
import { PictureUploader, formatFileList } from '~/components/PictureUploader';
import { FileUploader } from '~/components/FileUploader';
import { genValidConfig } from './pageConfig';
import './index.local.sass';

const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
  wrapperCol: { span: 20 },
};

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const setCardTitle = (title: string) => (
  <div className="card-title">
    <span className="title-icon">&nbsp;</span>
    <span>{title}</span>
  </div>
);

const AddOrEditInstitution = observer(() => {
  const location = useLocation();
  const history = useHistory();

  const querryParams = parse(location.search, { ignoreQueryPrefix: true });

  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    loading: false,
  }));

  const [form] = Form.useForm();

  // 获取表单数据
  const getFormValus = () => form.validateFields().then((values: any) => {
    const params = {
      id: state.id,
      ...values,
      organizationLogo: values.logoList.map((v: any) => v.response.data).toString(),
      uploadCase: values.fileList.map((v: any) => v.response.data).toString(),
      followIndustry: values.followIndustry.toString(),
      followCountry: values.followCountry.toString(),
    };

    delete params.logoList;
    delete params.fileList;

    return params;
  });

  const doSubmit = (type: number) => {
    getFormValus().then((params) => {
      state.loading = true;

      addApi.addInstitution(params).then(() => {
        message.success('success');

        // save and close
        if (type === 2) {
          history.push('/institution/list');
        }
      }).finally(() => {
        setTimeout(() => {
          state.loading = false;
        }, 2000);
      });
    }).catch(() => {
      message.error('validation error');
    });
  };

  const onSubmit = () => {
    doSubmit(1);
  };

  const onSaveAndClose = () => {
    doSubmit(2);
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const {
      organizationLogo,
      organizationName,
      countryId,
      orgType,
      specialityId,
      followIndustry,
      followCountry,
      headquartersOfficeAddress,
      officialWebsite,
      contact,
      phone,
      email,
      orgnisationIntroduction,
      accomplishments,
      uploadCase,
    } = formData;

    form.setFieldsValue({
      logoList: formatFileList(organizationLogo ? organizationLogo.split(',') : []),
      organizationName,
      countryId,
      orgType,
      specialityId,
      followIndustry: followIndustry ? followIndustry.split(',') : undefined,
      followCountry: followCountry ? followCountry.split(',') : undefined,
      headquartersOfficeAddress,
      officialWebsite,
      contact,
      phone,
      email,
      orgnisationIntroduction,
      accomplishments,
      fileList: formatFileList(uploadCase ? uploadCase.split(',') : []),
    });
  };

  // initForm
  const initForm = (id: string) => {
    addApi.getInstitution({ id }).then((res) => {
      fillForm(res.data);
    });
  };

  React.useEffect(() => {
    initForm(state.id);
  }, []);

  const { loading } = state;

  return (
    <div className="card-wrap">
      <Card
        title={
          setCardTitle('Institution Infomation')
        }
        className="card"
        {...cardConfig}
      >
        <Form form={form} layout="vertical" className="w-11/12">
          <Row>
            <Col span={12}>
              <FormItem
                label="LOGO"
                required
                name="logoList"
                rules={genValidConfig('LOGO')}
                {...formItemLayout}
              >
                <PictureUploader
                  max={1}
                  accept="image/jpeg,image/bmp,image/png "
                />
              </FormItem>

              <span className="text-xs cor-grey">Support JPG JPEG PNG BMP only</span>
            </Col>
          </Row>

          {/* line 2 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="organizationName"
                label="Institution Name"
                rules={genValidConfig('Institution Name')}
                {...formItemLayout}
              >
                <Input
                  placeholder="Please input"
                  allowClear
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="countryId"
                label="Country/Region"
                rules={genValidConfig('Country/Region')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="countryList"
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="orgType"
                label="Institution Type"
                rules={genValidConfig('Institution Type')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="orgType"
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 3 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="specialityId"
                label="Main Business"
                rules={genValidConfig('Main Business')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="specialityList"
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="followIndustry"
                label="Focus Industry (Multiple)"
                rules={genValidConfig('Focus Industry')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="industryList"
                  mode="multiple"
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="followCountry"
                label="Focus Country/Region (Multiple)"
                rules={genValidConfig('Focus Country/Region')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="countryList"
                  mode="multiple"
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 4 */}
          <Row>
            <Col span={24}>
              <FormItem
                name="headquartersOfficeAddress"
                label="Headquarters address"
                rules={genValidConfig('Headquarters address')}
              >
                <TextArea
                  className="w-full-fix"
                  placeholder="Please input (max: 5000 words)"
                  autoSize={{ minRows: 4 }}
                  maxLength={5000}
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 5 */}
          <Row>
            <Col span={24}>
              <FormItem
                name="officialWebsite"
                label="Institution Website"
                rules={genValidConfig('Institution Website')}
              >
                <Input
                  className="w-full-fix"
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 6 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="contact"
                label="Project Contact"
                rules={genValidConfig('Project Contact')}
                {...formItemLayout}
              >
                <Input
                  placeholder="Please input"
                  allowClear
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="phone"
                label="Phone Number"
                rules={genValidConfig('Phone Number')}
                {...formItemLayout}
              >
                <Input
                  placeholder="Please input"
                  allowClear
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                name="email"
                label="Email"
                rules={genValidConfig('Email')}
                {...formItemLayout}
              >
                <Input
                  placeholder="Please input"
                  allowClear
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 7 */}
          <Row>
            <Col span={24}>
              <FormItem
                name="orgnisationIntroduction"
                label="Institution Introduction"
                rules={genValidConfig('Institution Introduction')}
              >
                <TextArea
                  className="w-full-fix"
                  placeholder="Please input (max: 5000 words)"
                  autoSize={{ minRows: 4 }}
                  maxLength={5000}
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 8 */}
          <Row>
            <Col span={24}>
              <FormItem
                name="accomplishments"
                label="Project Performance"
                rules={genValidConfig('Project Performance')}
              >
                <TextArea
                  className="w-full-fix"
                  placeholder="Please input (max: 5000 words)"
                  autoSize={{ minRows: 4 }}
                  maxLength={5000}
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 9 */}
          <Row>
            <Col span={12}>
              <FormItem
                name="fileList"
                label="Related Cases"
                rules={genValidConfig('Related Cases')}
              >
                <FileUploader
                  multiple
                  accept="
                    application/zip,
                    application/vnd.rar,
                    application/msword,
                    application/vnd.openxmlformats-officedocument.wordprocessingml.document,
                    application/pdf
                  "
                />
              </FormItem>
              <div className="text-xs cor-grey">Support ZIP RAR DOC DOCX PDF only</div>
            </Col>
          </Row>

        </Form>
      </Card>

      <div>
        <Button
          type="primary"
          className="mr-2"
          onClick={onSubmit}
          disabled={loading}
        >
          Submit Certification
        </Button>

        <Button
          className="mr-2"
          onClick={onSaveAndClose}
          disabled={loading}
        >
          Save and Close
        </Button>
      </div>
    </div>
  );
});

export default AddOrEditInstitution;
